import { useState, useEffect, Fragment } from 'react'
import { useNavigate } from 'react-router-dom'
// import { useRecoilState } from 'recoil';
// import { userState } from '../../store'
import { FormOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx'
import {
  Card,
  Button,
  Tooltip,
  Tag,
  Table,
  message
} from 'antd'
import { userApi } from '../../api'
import moment from 'moment'

interface IProps {
  children?: any;
}

interface IUser {
  id: string;
  avatar: string;
  username: string;
  email: string;
  phone: string;
  role: string;
  status: number;
  created: number;
}

const displayTitleMap: any = {
  id: 'ID',
  avatar: '头像',
  username: '用户名',
  phone: '手机号',
  role: '角色',
  status: '状态',
  created: '创建时间'
}

export default function User (props: IProps) {
  // const [userInfo, setUserInfo] = useRecoilState(userState.userInfoAtom);

  const [data, setData] = useState({list: [], total: 0})
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [columns, setColumns] = useState([])
  const [pageTitle, setPageTitle] = useState('用户列表')

  const navigate = useNavigate()

  // 获取列表
  const getList = (params: any) => {
    userApi.getList(params).then((res: any) => {
      setData(res.data)
      setPageTitle('用户列表（'+ res.data.total +'）')
      const columnKeys = Object.keys(res.data.list[0])
      delete columnKeys[2]; // 不展示邮箱
      const columns = handleColumns(columnKeys)
      setColumns(columns)
    }) 
  }

  useEffect(() => {
    getList({page, pageSize})
  }, [page])

  useEffect(() => {
    getList({page, pageSize})
  }, [pageSize])

  // 处理要展示的列
  const handleColumns = (columnKeys: any) => {
    const columns = columnKeys.map((item: string) => {
      if (item === 'status') {
        return {
          title: displayTitleMap[item],
          key: item,
          render: (record: IUser) => {
            // 根据浏览量数字的大小，做一个条件渲染
            const statusMap: any = {
              0: '已注册',
              1: '已激活',
              2: '禁用',
              3: '已删除',
            }
            const colorMap: any = {
              0: 'blue',
              1: 'green',
              2: 'orange',
              3: 'grey',
            }
            return <Tooltip title="状态">
              <Tag color={ colorMap[record.status] }>{ statusMap[record.status] }</Tag>
            </Tooltip>
          }
        }
      }

      if (item === 'role') {
        return {
          title: displayTitleMap[item],
          key: item,
          render: (record: IUser) => {
            // 根据浏览量数字的大小，做一个条件渲染
            const statusMap: any = {
              1: "普通用户",
              2: "编辑",
              3: "管理员",
              4: "财务",
              5: "人事",
              6: "销售"
            }
            return <Tooltip title="角色">
              <Tag >{ statusMap[record.role] }</Tag>
            </Tooltip>
          }
        }
      }

      if (item === 'avatar') {
        return {
          title: displayTitleMap[item],
          key: item,
          render: (record: IUser) => {
            return <img style={{height: '50px'}} src={record.avatar} alt="头像"/>
          }
        }
      }

      if (item === 'created') {
        return {
          title: displayTitleMap[item],
          key: item,
          render: (record: IUser) => {
            const { created } = record
            return moment(created).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }

      return {
        title: displayTitleMap[item],
        key: item,
        dataIndex: item,
      }
    })

    columns.push({
      title: '操作',
      // dataIndex: 'action',
      key: 'action',
      fixed: 'right',
      render: (record: IUser) => {
        // console.log({text, record, index})
        return (
          <Button.Group>
            <Button size="small" type="primary" onClick={() => toEdit(record)}>编辑</Button>
          </Button.Group>
        )
      }
    })

    return columns
  }

  const toAdd = () => {
    message.warn('新增功能暂未开放')
    // navigate('/admin/project/add')
    // navigate('add')
  }

  // 跳转到编辑页面
  const toEdit = (record: IUser) => {
    message.warn('编辑功能暂未开放')
    // navigate(`/admin/user/edit/${record.id}`)
  }

  // 导出 Excel
  const exportExcel = () => {
    // console.log('exportExcel')
    // 组装数据
    const exportData = [Object.keys(data.list[0])]
    for (let i = 0; i < data.list.length; i++) {
      // exportData.push(Object.values(data.list[i]))

      // 对字段进行个性化处理，例如：创建时间
      exportData.push([
        data.list[i]['id'],
        data.list[i]['username'],
        data.list[i]['avatar'],
        data.list[i]['email'],
        data.list[i]['phone'],
        data.list[i]['role'],
        data.list[i]['status'],
        moment(data.list[i]['created']).format('YYYY-MM-DD HH:mm:ss'),
      ])
    }

    // 转成 workbook
		const ws = XLSX.utils.aoa_to_sheet(exportData);
		const wb = XLSX.utils.book_new();
		XLSX.utils.book_append_sheet(wb, ws, "SheetJS");

		// 生成 excel 文件
		XLSX.writeFile(wb, `user-${page}-${moment().format('YYYY-MM-DD-HH-mm-ss')}.xlsx`)
  }

  // 点击分页页码
  const onPageChange = (page: number, pageSize: number) => {
    setPage(page)
  }

  // 修改单页记录数
  const onPageSizeChange = (page: number, pageSize: number) => {
    setPageSize(pageSize)
  }

  return (
    <Fragment>
      <Card
        title={ pageTitle }
        bordered={false}
        extra={
          <div>
            <Button type="primary" ghost onClick={ toAdd }><FormOutlined />新增</Button>
            <Button onClick={ exportExcel }>导出Excel</Button>
          </div>
        } 
      >
        <Table
          tableLayout='auto' 
          rowKey={(record: IUser) => record.id} 
          dataSource={ data.list } 
          columns={ columns } 
          scroll={{ x: 1000 }}
          // loading={this.state.isLoading}
          pagination={{
            current: page,
            total: data.total,
            hideOnSinglePage: true,
            showQuickJumper: true,
            showSizeChanger: true,
            onChange: onPageChange,
            onShowSizeChange: onPageSizeChange,
            pageSizeOptions: ['10', '20', '30']
          }}
        />
      </Card>
    </Fragment>
  )
}
